
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/NetworkManager.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/pages/circle/CircleDetailPage.dart';
import 'package:huajianshe_app/pages/lesson/model/LessonCommentPage.dart';
import 'package:huajianshe_app/pages/lesson/model/LessonModel.dart';
import 'package:huajianshe_app/pages/main/MomentDetailPage.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/RoundedUnderlineTabIndicator.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/VideoPlayerUI.dart';
import 'package:huajianshe_app/widget/WebViewPage.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'package:oktoast/oktoast.dart';
import 'package:video_player/video_player.dart';

import 'ChapterListPage.dart';

class LessonDetailPage extends StatefulWidget {

  final int? id;

  const LessonDetailPage(this.id, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LessonDetailPageState();
  }
}

class _LessonDetailPageState extends BaseState<LessonDetailPage> with TickerProviderStateMixin {

  // late VideoPlayerController _videoPlayerController1;
  final FijkPlayer player = FijkPlayer();
  late SystemUiOverlayStyle overlayStyle;
  late double appbarOpacity;
  late ScrollController scrollController;
  late TabController tabController;
  LessonDetailData? data;
  late int offset = 0;
  double playerHeight = 200;

  @override
  void initState() {
    super.initState();
    appbarOpacity = 0;
    overlayStyle = SystemUiOverlayStyle.light;
    scrollController = ScrollController();
    scrollController.addListener(() => {_onScroll()});
    tabController = TabController(length: 3, vsync: this);
    load();
  }

  void _onScroll() {
    // print('position ${controller.position} offset ${controller.offset}');
    int newOffset = scrollController.offset.toInt() - 50;
    if (newOffset > 50) newOffset = 50;
    if (newOffset < 0) newOffset = 0;
    if (offset == newOffset) return;
    offset = newOffset;
    this.appbarOpacity = offset.toDouble() * 2 * 0.01;
    print('appbarOpacity ${appbarOpacity} offset ${offset}');
    if (this.appbarOpacity > 0.5 && this.overlayStyle != SystemUiOverlayStyle.dark) {
      this.overlayStyle = SystemUiOverlayStyle.dark;
    }
    if (this.appbarOpacity <= 0.5 && this.overlayStyle != SystemUiOverlayStyle.light) {
      this.overlayStyle = SystemUiOverlayStyle.light;
    }
    setState(() { });
  }
  
  load() {
    sendReq(Api.lessonDetail(), LessonDetailResp(), data: {'id': widget.id}, doNotShowProgressBar: true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is LessonDetailResp) {
      this.data = t.data;
      if (this.data?.chapterType == 1) { //如果有导论，就播放视频，否则显示封面
        initializePlayer();
      }
      setState(() => null);
    } else if (path.contains(Api.doLike().path) && code == 0) {
      setState(() {});
    } else if (t is BaseResp) {
      if (path.contains('Circle/joinCircle')) { //加入圈子
        if (t.code == 0) { //成功
          data?.circleInfo?.isJoin = 1;
          setState(() => null);
        }
        Toast.show(msg);
      }
    }
  }

  @override
  void dispose() {
    // _videoPlayerController1.dispose();
    player.stop();
    player.release();
    player.dispose();
    super.dispose();
  }

  Future<void> initializePlayer() async {
    // _videoPlayerController1 = VideoPlayerController.network(
    //     'https://assets.mixkit.co/videos/preview/mixkit-daytime-city-traffic-aerial-view-56-large.mp4');
    // // _videoPlayerController2 = VideoPlayerController.network(
    // //     'https://assets.mixkit.co/videos/preview/mixkit-a-girl-blowing-a-bubble-gum-at-an-amusement-park-1226-large.mp4');
    // await Future.wait([
    //   _videoPlayerController1.initialize(),
    //   _videoPlayerController1.play()
    // ]);
    await player.setDataSource(data?.videoUrl ?? '', autoPlay: true);
    // await player.setDataSource('https://sample-videos.com/video123/flv/240/big_buck_bunny_240p_10mb.flv', autoPlay: true);
    player.prepareAsync();
    player.addListener(_playerValueChanged);
  }

  @override
  Widget build(BuildContext context) {
    print('height: ${playerHeight + 160 + 1 + 170 + 10}');
    return
      Scaffold(
        body: Column(children: [
          Expanded(child: Stack(children: [
            NestedScrollView(
              controller: scrollController,
              body: buildTabBarView(),
              headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverAppBar(
                      backgroundColor: Colors.white,
                      automaticallyImplyLeading: false,
                      // title: Text('2222'),
                      pinned: true,
                      expandedHeight: playerHeight + 160 + 1 + 170 + 10, //550,
                      elevation: 0,
                      flexibleSpace: FlexibleSpaceBar(
                        collapseMode: CollapseMode.pin,
                        background: Container( //头部整个背景颜色
                            height: double.infinity,
                            child: Column(mainAxisSize: MainAxisSize.min, children: [
                              Stack(children: [
                                buildPlayer(), //playerHeight
                              ]),
                              buildDetail(), // 160
                              D(), // 1
                              buildChapters(), // 170
                              Container(width: double.infinity, height: 10, color: C.grayF6) // 10
                            ])
                        ),
                      ),
                      bottom: buildTabBar()
                  )
                ];
              },
            ),
            CAppBar(backImgUrl: 'ic_white_arrow', actions: [LoadImage('ic_white_share')]),
            Opacity(opacity: appbarOpacity, child: CAppBar(backImgUrl: 'ic_black_arrow', bgColor: Colors.white,
              actions: [LoadImage('ic_black_share')], title: data?.name ?? '',))
          ])),
          buildBottom()
        ]),
    );
  }

  void _playerValueChanged() {
    if(player.state == FijkState.prepared){
      print('prepared: ${player.value.size}');
      double width = MediaQuery.of(context).size.width;
      double aspectRatio = (player.value.size?.width ?? width) / (player.value.size?.height ?? 200);
      playerHeight = width / aspectRatio + 1;
      print('width: $width, ratio: ${aspectRatio}, playerHeight: $playerHeight');
      setState(() => {});
    } else {
      print('other');
    }
  }

  Widget buildPlayer() {
    if (data?.chapterType == 1) {
      return FijkView(width: double.infinity, height: playerHeight, player: player, color: Colors.black,
        panelBuilder: (FijkPlayer player, FijkData data1, BuildContext context, Size viewSize, Rect texturePos) {
          return VideoPlayerUI(player: player, buildContext: context, viewSize: viewSize, texturePos: texturePos, title: data?.name);
        });
    } else {
      return LoadImage(data?.cover, width: double.infinity, height: playerHeight);
    }
  }
  
  Widget buildDetail() {
    return
      Container(width: double.infinity, height: 160, padding: EdgeInsets.all(13),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(data?.name ?? '', style: TS(16, C.gray333, fontWeight: FontWeight.bold),),
            H(9),
            Row(children: [
              Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                Text('共${data?.totalChapters ?? ''}节，已更新${data?.currentChapter ?? ''}节', style: TS(12, C.gray333),),
                H(8),
                Row(children: [
                  RoundedCornerWidget(height: 21, child: Row(children: [
                    W(5),
                    LoadImage('ic_play_lesson_11.png'),
                    W(5),
                    Text('播放:${data?.playNum}', style: TS(11, C.gray666),),
                    W(5)
                  ]),radius: 2, backgroundColor: C.grayF6),
                  W(5),
                  RoundedCornerWidget(height: 21, child: Row(children: [
                    W(5),
                    LoadImage('ic_buy_11.png'),
                    W(5),
                    Text('购买:${data?.saleNum}', style: TS(11, C.gray666),),
                    W(5)
                  ]),radius: 2, backgroundColor: C.grayF6,)
                ]),
              ])),
              SmartButton(width: 120, height: 38, radius: 19, text: data?.circleInfo?.isJoin == 1 ? '进入同学圈' : '加入同学圈',
                drawableLeft: data?.circleInfo?.isJoin == 1 ? null : LoadImage('ic_white_add'),
                drawablePadding: 5, onPressed: join,)
            ]),
            H(12),
            Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
              SmartButton(text: '${data?.commentNum ?? 0}', fontSize: 12, textColor: C.gray333, backgroundColor: Colors.transparent, borderColor: Colors.transparent,
              height: 45, drawableTop: LoadImage('ic_black_comment'), drawablePadding: 5, onPressed: comment),
              SmartButton(text: '${data?.collectNum ?? 0}', fontSize: 12, textColor: C.gray333, backgroundColor: Colors.transparent, borderColor: Colors.transparent,
                  height: 45, drawableTop: LoadImage('${data?.isCollected == 1 ? 'ic_lesson_favorite' : 'ic_lesson_unfavorite'}'), drawablePadding: 5, onPressed: favorite),
              SmartButton(text: '分享', fontSize: 12, textColor: C.gray333, backgroundColor: Colors.transparent, borderColor: Colors.transparent,
                  height: 45, drawableTop: LoadImage('ic_black_share'), drawablePadding: 5, onPressed: share),
            ],)
          ]),
      );
  }

  Widget buildChapters() {
    List<Widget> widgets = [];
    for (int i = 0; i < (data?.chapters?.length ?? 0); i++) {
      if (i > 0) {
        widgets.add(W(15));
      }
      widgets.add(
          GestureDetector(onTap: () { play(); },
              child: Container(width: 140, child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
                ClipRRect(borderRadius: BorderRadius.circular(3), child: LoadImage(data?.chapters?[i].cover, width: 140, height: 78,)),
                H(8),
                Text(data?.chapters?[i].name ?? '', style: TS(13, C.gray333), maxLines: 1, overflow: TextOverflow.ellipsis,)
              ]))
          )
      );
    }
    return
      Container(width: double.infinity, height: 170, padding: EdgeInsets.all(13),
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text('选集', style: TS(17, C.gray333, fontWeight: FontWeight.bold)),
            H(14),
            SingleChildScrollView(scrollDirection: Axis.horizontal,
                child: Row(children: [
                  ...widgets
                ])
            )
          ])
      );
  }

  Widget buildTabBarView() {
    return
      TabBarView(controller: tabController, children: [
        Padding(padding: EdgeInsets.only(top: 10), child: WebViewPage(data?.masterH5, null, showAppBar: false)), //
        Padding(padding: EdgeInsets.only(top: 10), child: WebViewPage(data?.lessonH5, null, showAppBar: false)),
        Padding(padding: EdgeInsets.only(top: 0), child: ChapterListPage(data?.chapters)),
      ]);
  }

  PreferredSizeWidget buildTabBar() {
    return
      PreferredSize(preferredSize: Size.fromHeight(32),
          child: RoundedCornerWidget(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            H(10),
            Padding(padding: EdgeInsets.only(left: 8, top: 2),
                child: TabBar(
                  labelPadding: EdgeInsets.only(left: 6, right: 6, bottom: 2),
                  indicatorWeight: 0,
                  indicatorSize: TabBarIndicatorSize.label,
                  indicator: RoundedUnderlineTabIndicator(
                    insets: EdgeInsets.only(left: 0, top: 0, bottom: -8),
                    borderSide: BorderSide(width: 1, color: C.primary),
                  ),
                  isScrollable: true,
                  controller: tabController,
                  labelColor: C.gray333,
                  unselectedLabelColor: C.gray999,
                  labelStyle: TS(15, C.gray333, fontWeight: FontWeight.bold),
                  unselectedLabelStyle: TS(15, C.gray999),
                  tabs: [Text('大师介绍'), Text('课程介绍'), Text('章节列表')]
              )
            ),
            H(7),
            D(),
          ]), backgroundColor: Colors.white, radius: 0, cornerPosition: 0, height: 44, width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 0),)
      );
  }

  Widget buildBottom() {
    if (data?.needBuy == 0) return H(0);
    String integer = '0';
    String digit = '00';
    List<String> arr = data?.price?.split('.') ?? ['0', '00'];
    if (arr.length == 2) {
      integer = arr[0];
      digit = arr[1];
    }
    return
      Container(width: double.infinity, height: 55, child: Row(children: [
        W(15),
        RichText(text: TextSpan(text: '价格', style: TS(13, C.primary), children: [
          TextSpan(text: ' ¥ ', style: TS(13, C.primary)),
          TextSpan(text: integer, style: TS(21, C.primary)),
          TextSpan(text: '.$digit', style: TS(13, C.primary)),
        ])),
        // Text('价格', style: TS(13, C.gray333),),
        // Text('¥${data?.price}', style: TS(13, C.primary),),
        Spacer(),
        SmartButton(width: 210, height: 44, radius: 22, text: '立即购买', textColor: Colors.white, fontSize: 15,
          onPressed: () => buy()),
        W(8)
      ]), decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [
            BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.08), blurRadius: 11.0, spreadRadius: 0.0, offset: Offset(1, 0)),
          ]
      ),);
  }

  favorite() {
    var data2 = {
      'aim_type': '5',
      'aim_sn': this.data?.lessonSn,
      'like_type': '2'
    };
    NetworkParams api = Api.doLike();
    sendRequest2(BaseResp(), path: api.path, method: api.method, isForm: api.isForm,
        data: data2, callback: LikeCallback2(this, () {
          if (data?.isCollected == 1) {
            data?.isCollected = 0;
            data?.collectNum = (data?.collectNum ?? 1) - 1;
          } else {
            data?.isCollected = 1;
            data?.collectNum = (data?.collectNum ?? 0) + 1;
          }
        })
    );
  }

  pauseCurrentPlayer() {
    player.pause();
  }

  join() {
    if (data?.circleInfo?.isJoin == 1) { // 如果已经加入了，直接进圈子
      pauseCurrentPlayer();
      AppNavigator.push(context, RouteName.CIRCLE_DETAIL, arguments: {'circleDetailType': CircleDetailType.inner, 'circleId': data?.circleInfo?.circleId});
    } else {
      sendReq(Api.circleJoin(), BaseResp(), data: {'circle_id': data?.circleInfo?.circleId}, doNotShowProgressBar: false);
    }
  }

  buy() {
  }

  comment() {
    DialogUtil.showBottomDialogV2(context, LessonCommentPage(data?.lessonSn), height: 0.8,
        radius: 13, cornerPosition: 3, margin: EdgeInsets.symmetric(horizontal: 5));
  }

  share() {

  }

  play() {
    pauseCurrentPlayer();
    AppNavigator.push(context, RouteName.VIDEO_PLAYER);
  }
}

class LikeCallback2 extends NetworkCallback {

  final NetworkCallback originalCallback;
  final void Function() onSuccess ;

  LikeCallback2(this.originalCallback, this.onSuccess);

  @override
  void onReqError(int code, String msg) { originalCallback.onReqError(code, msg); }

  @override
  void onReqFinish() { originalCallback.onReqFinish(); }

  @override
  void onReqStart() {}

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (path.contains(Api.doLike().path) && code == 0) {
      onSuccess();
      originalCallback.onReqSuccess(t, code, msg, path);
    }
    showToast(msg);
  }
}